package com.zuoyy.admin.system.service.impl;

import com.zuoyy.admin.system.service.BaseInterface;
import com.zuoyy.admin.system.service.FileInterface;
import com.zuoyy.common.enums.StatusEnum;
import com.zuoyy.common.utils.EntityBeanUtil;
import com.zuoyy.common.utils.FileUtil;
import com.zuoyy.common.vo.JsonResponse;
import com.zuoyy.modules.system.domain.SysFile;
import com.zuoyy.modules.system.query.FileQuery;
import com.zuoyy.modules.system.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 
 */
@Service
public class FileInterfaceImpl extends BaseInterface implements FileInterface {

    @Autowired
    private FileService fileService;


    @Override
    public JsonResponse getListPage(FileQuery query) {
        Page<SysFile> page = fileService.getPageList(query);
        List<SysFile> list = page.getContent();
        return JsonResponse.success(setQueryResult(query.getDraw(), (int) page.getTotalElements(),list));
    }

    @Override
    public JsonResponse saveOrUpdate(SysFile domain) {
        if (!StringUtils.isEmpty(domain.getId())) {
            SysFile file = fileService.findById(domain.getId());
            EntityBeanUtil.copyProperties(file, domain);
        }
        fileService.save(domain);
        return JsonResponse.success();
    }


    @Override
    @Transactional
    public JsonResponse updateStatus(StatusEnum statusEnum, List<String> ids) {
        if (fileService.updateStatus(statusEnum, ids)) {
            if(statusEnum == StatusEnum.DELETE){
                for(String id : ids){
                    SysFile file = fileService.findById(id);
                    try {
                        FileUtil.delFile(file.getPath());
                    }catch (Exception e){}
                }
            }
            return JsonResponse.success(statusEnum.message + "成功");
        } else {
            return JsonResponse.error(statusEnum.message + "失败，请重新操作");
        }
    }


    @Override
    @Transactional
    public JsonResponse delByBusinessId(String businessId) {
        if (fileService.delByBusinessId(businessId)) {
            return JsonResponse.success("删除成功");
        } else {
            return JsonResponse.error("失败，请重新操作");
        }
    }
}